<template>
  <!-- 钢丝 -->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="生产日期">
        <el-date-picker
          v-model="daterangeDt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="厂区" prop="factory">
        <el-input
          v-model="queryParams.factory"
          placeholder="请输入厂区"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="当班人员" prop="operator">
        <el-input
          v-model="queryParams.operator"
          placeholder="请输入当班人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="记录人" prop="recordPerson">
        <el-input
          v-model="queryParams.recordPerson"
          placeholder="请输入记录人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查人" prop="checkPeople">
        <el-input
          v-model="queryParams.checkPeople"
          placeholder="请输入检查人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bm:steelWire:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bm:steelWire:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bm:steelWire:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bm:steelWire:export']"
        >导出</el-button>
      </el-col>
      <!-- 添加图表显示按钮 -->
      <el-col :span="18" style="text-align: right;">
        <el-button
          type="primary"
          icon="el-icon-data-analysis"
          size="mini"
          @click="openChartDialog"
          style="float: right;"
        >图表显示</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="steelWireList" @selection-change="handleSelectionChange" :show-summary="true" :summary-method="getSummaries" @sort-change="handleSortChange">
      <el-table-column type="selection" width="80" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="55"/>
      <el-table-column label="生产日期" align="center" prop="dt" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产出重量" align="center" prop="weightVal" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseFloat(scope.row.weightVal).toFixed(3) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重量单位" align="center" prop="weightUnit">
        <template slot-scope="scope">
          <el-tag :type="getWeightUnitTagType(scope.row.weightUnit)">{{ scope.row.weightUnit }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="班次" align="center" prop="team" />
      <el-table-column label="当班人员" align="center" prop="operator" />
      <el-table-column label="记录人" align="center" prop="recordPerson" />
      <el-table-column label="检查人" align="center" prop="checkPeople" />
      <el-table-column label="厂区" align="center" prop="factory" />
      <el-table-column label="录入时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产票据" align="center" prop="fileUrl" width="100">
        <template slot-scope="scope">
          <div v-if="scope.row.fileUrl">
            <el-tooltip content="点击查看图片" placement="top">
              <i class="el-icon-picture" style="font-size: 20px; color: #409EFF; cursor: pointer;" 
                 @click="handleImagePreview(scope.row.fileUrl)"></i>
            </el-tooltip>
          </div>
          <span v-else>暂无票据</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bm:steelWire:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bm:steelWire:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改钢丝对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="生产时间" prop="dt">
              <el-date-picker clearable
                v-model="form.dt"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择生产时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投入重量" prop="weightVal">
              <el-input-number
                v-model="form.weightVal" 
                controls-position="right"
                :precision="3"
                :step="0.001"
                :min="0"
                placeholder="请输入投入重量" 
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="11">
            <el-form-item label="重量单位" prop="weightUnit">
              <el-select v-model="form.weightUnit" placeholder="请选择重量单位">
                <el-option
                  v-for="item in dict.type.pro_weight_unit"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-tooltip class="item" effect="dark" content="重量单位选择条时，投入重量为每条轮胎重量" placement="top-start">
            <i class="el-icon-info" style="font-size: 18px;"></i>
          </el-tooltip>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班组" prop="team">
              <el-select v-model="form.team" size="medium" placeholder="请选择班组">
                <el-option
                  v-for="item in dict.type.pro_team_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当班人员" prop="operator">
              <el-input v-model="form.operator" placeholder="请输入当班人员" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录人" prop="recordPerson">
              <el-input v-model="form.recordPerson" placeholder="请输入记录人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验人" prop="checkPeople">
              <el-input v-model="form.checkPeople" placeholder="请输入检验人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="厂区" prop="factory">
              <el-select v-model="form.factory" placeholder="请选择厂区">
                <el-option
                  v-for="dict in dict.type.company_dict"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-tooltip class="item" effect="dark" content="请输入生产数据对应的厂区" placement="top-start">
            <i class="el-icon-info" style="font-size: 18px;"></i>
          </el-tooltip>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="form.remark" 
                placeholder="请输入备注" 
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="30">
            <el-form-item label="生产票据">
            <el-upload
              class="upload-demo"
              :action="uploadFileUrl"
              :headers="headers"
              :file-list="fileList"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :before-upload="beforeAvatarUpload"
              multiple
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过2MB</div>
            </el-upload>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog title="票据图片预览" :visible.sync="previewDialogVisible" width="50%">
      <el-carousel v-if="previewImages.length > 1" height="500px">
        <el-carousel-item v-for="(url, index) in previewImages" :key="index">
          <div class="image-container">
            <img :src="url" style="max-width: 100%; max-height: 500px; cursor: pointer;" @click="openFullScreen(url)" />
          </div>
        </el-carousel-item>
      </el-carousel>
      <div v-else-if="previewImages.length === 1" class="image-container">
        <img :src="previewImages[0]" style="max-width: 100%; max-height: 500px; cursor: pointer;" @click="openFullScreen(previewImages[0])" />
      </div>
      <div class="preview-info" v-if="previewImages.length > 0">
        <i class="el-icon-zoom-in"></i> 点击图片可全屏查看
      </div>
    </el-dialog>

    <!-- 全屏图片预览 -->
    <el-dialog 
      :visible.sync="fullScreenVisible" 
      append-to-body 
      :modal="true"
      :show-close="true"
      :fullscreen="true"
      custom-class="fullscreen-dialog">
      <div class="fullscreen-container" @wheel.prevent="handleWheel">
        <img :src="fullScreenImage" class="fullscreen-image" :style="{ transform: `scale(${zoomLevel})` }" />
      </div>
    </el-dialog>

    <!-- 图表对话框 -->
    <el-dialog 
      title="钢丝产出数据图表" 
      :visible.sync="chartDialogVisible" 
      width="65%" 
      :before-close="handleChartClose"
      custom-class="chart-dialog">
      <div class="chart-container">
        <div ref="chartContainer" style="width: 100%; height: 500px;"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSteelWire, getSteelWire, delSteelWire, addSteelWire, updateSteelWire } from "@/api/mes/bm/steelWire";
import { getToken } from "@/utils/auth";
import { mapGetters } from 'vuex';
import * as echarts from 'echarts'; // 引入echarts

export default {
  name: "SteelWire",
  dicts: ['pro_weight_unit', 'pro_team_type', 'company_dict'],
  computed: {
    ...mapGetters([
      'nickName'
    ])
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 钢丝表格数据
      steelWireList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标识时间范围
      daterangeDt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dt: null,
        beginDt: null,
        endDt: null,
        factory: null,
        operator: null,
        recordPerson: null,
        checkPeople: null,
        dtSortFlag: 0,         // 生产日期排序标志
        weightValSortFlag: 0    // 产出重量排序标志
      },
      // 表单参数
      form: {},
      // 上传的图片路径
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/uploadMinio",
      // 设置上传头
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 上传的文件列表
      fileList: [],
      // 上传的文件URL列表
      fileUrlList: [],
      // 单个图片预览
      imageUrl: null,
      // 表单校验
      rules: {
        dt: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],        factory: [
          { required: true, message: "厂区不能为空", trigger: "blur" }
        ],        recordPerson: [
          { required: true, message: "记录人不能为空", trigger: "blur" }
        ],        checkPeople: [
          { required: true, message: "检查人不能为空", trigger: "blur" }
        ],        team: [
          { required: true, message: "班组不能为空", trigger: "blur" }
        ],        weightUnit: [
          { required: true, message: "重量单位不能为空", trigger: "blur" }
        ],        weightVal: [
          { required: true, message: "重量值不能为空", trigger: "blur" }
        ],        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],        isDelete: [
          { required: true, message: "删除标识不能为空", trigger: "blur" }
        ]      
      },
      // 预览图片列表
      previewImages: [],
      // 图片预览对话框
      previewDialogVisible: false,
      // 全屏预览相关
      fullScreenVisible: false,
      fullScreenImage: '',
      zoomLevel: 1, // 新增：缩放级别
      // 图表相关
      chartDialogVisible: false,
      chartType: 'bar', // 默认为柱状图
      chart: null, // 图表实例
      resizeHandler: null // 用于监听窗口大小变化
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询钢丝列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDt && '' != this.daterangeDt) {
        this.queryParams.params["beginDt"] = this.daterangeDt[0];
        this.queryParams.params["endDt"] = this.daterangeDt[1];
      }
      listSteelWire(this.queryParams).then(response => {
        this.steelWireList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dt: null,
        weightVal: 0.000,
        weightUnit: null,
        numVal: 0,
        factory: 'HEADQUARTERS',
        team: null,
        operator: null,
        recordPerson: null,
        checkPerson: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        fileUrl: null
      };
      this.resetForm("form");
      // 重置上传文件列表
      this.fileList = [];
      this.fileUrlList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.daterangeDt = [];
      this.queryParams.beginDt = null;
      this.queryParams.endDt = null;
      this.queryParams.dtSortFlag = 0;
      this.queryParams.weightValSortFlag = 0;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 设置默认记录人
      this.form.recordPerson = this.nickName;
      
      // 设置日期为昨天
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      const year = yesterday.getFullYear();
      const month = String(yesterday.getMonth() + 1).padStart(2, '0');
      const day = String(yesterday.getDate()).padStart(2, '0');
      this.form.dt = `${year}-${month}-${day}`;
      
      // 使用最新一条数据的字段值
      if (this.steelWireList && this.steelWireList.length > 0) {
        // 获取列表中的第一条记录（最新记录）
        const latestRecord = this.steelWireList[0];
        // 填充重量单位、当班人员、班次、检验人和厂区
        this.form.weightUnit = latestRecord.weightUnit;
        this.form.operator = latestRecord.operator;
        this.form.team = latestRecord.team;
        this.form.checkPeople = latestRecord.checkPeople;
        this.form.factory = latestRecord.factory;
      }

      this.open = true;
      this.title = "添加钢丝记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSteelWire(id).then(response => {
        this.form = response.data;
        // 初始化文件列表
        this.initFileList(this.form.fileUrl);
        this.open = true;
        this.title = "修改钢丝";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将文件URL列表转为字符串保存到form.fileUrl
          if (this.fileUrlList.length > 0) {
            this.form.fileUrl = JSON.stringify(this.fileUrlList);
          } else {
            // 文件列表为空时，清空fileUrl字段
            this.form.fileUrl = null;
          }
          
          if (this.form.id != null) {
            updateSteelWire(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSteelWire(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除钢丝编号为"' + ids + '"的数据项？').then(function() {
        return delSteelWire(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const timestamp = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      
      this.download('mes/bm/steelWire/export', {
        ...this.queryParams
      }, `钢丝_${timestamp}.xlsx`)
    },
    handleAvatarSuccess(res, file) {
      // 保存最后一个上传的图片用于预览
      this.imageUrl = res.url;
      // 添加到文件URL列表
      this.fileUrlList.push(res.url);
    },
    // 移除文件时从列表中删除
    handleRemove(file, fileList) {
      const fileUrl = file.response ? file.response.url : file.url;
      const index = this.fileUrlList.indexOf(fileUrl);
      if (index !== -1) {
        this.fileUrlList.splice(index, 1);
      }
      // 更新预览图片
      if (this.fileUrlList.length > 0) {
        this.imageUrl = this.fileUrlList[this.fileUrlList.length - 1];
      } else {
        this.imageUrl = null;
      }
    },
    // 文件上传前的钩子
    beforeAvatarUpload(file) {
      const isImage = file.type.indexOf('image') !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传的文件只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传的图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    // 获取重量单位标签类型
    getWeightUnitTagType(weightUnit) {
      switch(weightUnit) {
        case '吨':
          return 'primary';
        case '千克':
          return 'success';
        case '条':
          return 'warning';
        default:
          return 'info';
      }
    },
    // 初始化文件列表
    initFileList(fileUrl) {
      if (fileUrl) {
        try {
          // 尝试解析JSON格式的fileUrl
          const urls = JSON.parse(fileUrl);
          if (Array.isArray(urls)) {
            this.fileUrlList = urls;
            // 构建文件列表
            this.fileList = urls.map((url, index) => ({
              name: `文件${index + 1}`,
              url: url
            }));
            // 设置预览图片
            if (urls.length > 0) {
              this.imageUrl = urls[0];
            }
          } else {
            // 如果不是数组，可能是旧数据，只有一个URL
            this.fileUrlList = [fileUrl];
            this.fileList = [{
              name: '文件1',
              url: fileUrl
            }];
            this.imageUrl = fileUrl;
          }
        } catch (e) {
          // 解析失败，可能是旧数据格式
          this.fileUrlList = [fileUrl];
          this.fileList = [{
            name: '文件1',
            url: fileUrl
          }];
          this.imageUrl = fileUrl;
        }
      } else {
        this.fileUrlList = [];
        this.fileList = [];
        this.imageUrl = null;
      }
    },
    // 预览图片
    handleImagePreview(fileUrl) {
      try {
        if (typeof fileUrl === 'string') {
          try {
            // 尝试解析JSON字符串
            const urls = JSON.parse(fileUrl);
            if (Array.isArray(urls)) {
              this.previewImages = urls;
            } else {
              this.previewImages = [fileUrl];
            }
          } catch (e) {
            // 解析失败，可能是单个URL字符串
            this.previewImages = [fileUrl];
          }
        } else {
          this.previewImages = [];
        }
        this.previewDialogVisible = true;
      } catch (error) {
        console.error("预览图片失败:", error);
        this.$message.error("预览图片失败");
      }
    },
    // 新增：处理鼠标滚轮事件
    handleWheel(event) {
      // 向上滚动放大，向下滚动缩小
      if (event.deltaY < 0) {
        this.zoomLevel = Math.min(this.zoomLevel + 0.1, 3); // 设置最大缩放为3倍
      } else {
        this.zoomLevel = Math.max(this.zoomLevel - 0.1, 0.5); // 设置最小缩放为0.5倍
      }
    },
    // 在打开全屏对话框时重置缩放级别
    openFullScreen(imageUrl) {
      this.fullScreenImage = imageUrl;
      this.fullScreenVisible = true;
      this.zoomLevel = 1; // 重置缩放级别
    },
    // 添加表格合计行计算方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        
        if (column.property === 'weightVal') {
          const values = data.map(item => Number(item.weightVal));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + value;
              } else {
                return prev;
              }
            }, 0).toFixed(3);
          } else {
            sums[index] = 'N/A';
          }
        } else {
          sums[index] = '';
        }
      });
      
      return sums;
    },
    /** 处理表格排序变化 */
    handleSortChange(column) {
      // 首先将所有排序标志重置为0
      this.queryParams.dtSortFlag = 0;
      this.queryParams.weightValSortFlag = 0;
      
      // 然后根据当前排序列设置对应的排序标志
      if (column.prop === "dt") {
        if (column.order === "ascending") {
          this.queryParams.dtSortFlag = 1;
        } else if (column.order === "descending") {
          this.queryParams.dtSortFlag = -1;
        }
      } else if (column.prop === "weightVal") {
        if (column.order === "ascending") {
          this.queryParams.weightValSortFlag = 1;
        } else if (column.order === "descending") {
          this.queryParams.weightValSortFlag = -1;
        }
      }
      this.getList();
    },
    
    // 打开图表对话框
    openChartDialog() {
      this.chartDialogVisible = true;
      // 在对话框打开后初始化图表
      this.$nextTick(() => {
        this.initChart();
      });
    },
    
    // 关闭图表对话框
    handleChartClose() {
      if (this.chart) {
        this.chart.dispose();
        this.chart = null;
      }
      // 移除resize事件监听器
      if (this.resizeHandler) {
        window.removeEventListener('resize', this.resizeHandler);
      }
      this.chartDialogVisible = false;
    },
    
    // 初始化图表
    initChart() {
      if (this.chart) {
        this.chart.dispose();
      }
      
      // 获取DOM元素
      const chartDom = this.$refs.chartContainer;
      this.chart = echarts.init(chartDom);
      
      // 准备数据
      const chartData = this.prepareChartData();
      
      // 设置图表选项
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          right: 20,
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: ['产出量(吨)']
        },
        xAxis: [
          {
            type: 'category',
            data: chartData.xAxisData,
            axisPointer: {
              type: 'shadow'
            },
            axisLabel: {
              interval: 0,
              rotate: 30,
              formatter: function(value) {
                return value.substring(0, 10) + '\n' + value.substring(11);
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '产出量(吨)',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '产出量(吨)',
            type: 'bar',
            data: chartData.weightData,
            itemStyle: {
              color: '#409EFF'
            },
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '100px',
          top: '70px',
          containLabel: true
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100,
            xAxisIndex: [0]
          },
          {
            type: 'slider',
            start: 0,
            end: 100,
            height: 30,
            bottom: 10,
            xAxisIndex: [0],
            borderColor: '#e0e0e0',
            backgroundColor: '#f8f8f8',
            fillerColor: 'rgba(64, 158, 255, 0.3)',
            handleIcon: 'M 0.5 0.5 H 8.5 V 15.5 H 0.5 Z',
            handleSize: '100%',
            handleStyle: {
              color: '#409EFF',
              borderColor: '#c5c5c5',
              borderWidth: 1,
              shadowBlur: 0,
              opacity: 0.8
            },
            textStyle: {
              color: '#999'
            }
          }
        ]
      };
      
      // 应用选项
      this.chart.setOption(option);
      
      // 响应图表容器大小变化
      this.$nextTick(() => {
        this.chart.resize();
      });
      
      // 响应窗口调整大小
      this.resizeHandler = () => {
        if (this.chart && this.chartDialogVisible) {
          this.chart.resize();
        }
      };
      window.addEventListener('resize', this.resizeHandler);
    },
    
    // 准备图表数据
    prepareChartData() {
      // 克隆并排序数据以确保按时间顺序
      const sortedData = [...this.steelWireList].sort((a, b) => {
        const dateA = new Date(a.dt);
        const dateB = new Date(b.dt);
        return dateA - dateB;
      });
      
      // 提取横坐标和数据值
      const xAxisData = [];
      const weightData = [];
      
      sortedData.forEach(item => {
        const date = this.parseTime(item.dt, '{y}-{m}-{d}');
        const team = item.team || '';
        const label = `${date} ${team}`;
        
        xAxisData.push(label);
        
        // 处理重量，确保统一为吨
        let weight = parseFloat(item.weightVal);
        if (item.weightUnit === '千克') {
          weight = weight / 1000;
        } else if (item.weightUnit === '条') {
          weight = (weight * 1) / 1000; // 如果单位是条则直接转换
        }
        weightData.push(parseFloat(weight.toFixed(3)));
      });
      
      return {
        xAxisData,
        weightData
      };
    }
  }
};
</script>

<style>
  .upload-demo .el-upload-list {
    display: flex;
    flex-wrap: wrap;
  }
  
  .upload-demo .el-upload-list .el-upload-list__item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  
  .upload-demo .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
  }
  
  .fullscreen-dialog {
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.9);
  }
  
  .fullscreen-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
  }
  
  .fullscreen-image {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
  }
  
  .image-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .preview-info {
    text-align: center;
    margin-top: 10px;
    color: #909399;
  }
  
  /* 图表相关样式 */
  .chart-dialog .el-dialog__body {
    padding: 20px !important;
    height: calc(80vh - 110px) !important;
    overflow: hidden;
  }
  
  .chart-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .chart-toolbar {
    margin-bottom: 15px;
    text-align: right;
  }
  
  .chart-container > div:last-child {
    flex: 1;
    height: calc(100% - 40px) !important;
    min-height: 400px;
  }
</style>
